//
//  WQCAddViewController.m
//  renxinghuan
//
//  Created by 王晓民 on 2018/3/21.
//  Copyright © 2018年 吴清翠. All rights reserved.
//

#import "WQCAddViewController.h"
#import "configuration.h"
#import "WYCbankPickerView.h"
#import "WYCBankModel.h"
#import "PickerDateViewController.h"
#import "WYCDayPickerView.h"
@interface WQCAddViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    PickerDateViewController * pickerView;
    UIButton  *bankname;
}
@property(nonatomic,strong)UITableView  *editTableView ;
@property(nonatomic,strong)NSArray  *oneArr;
@property(nonatomic,strong)NSArray  *twoArr;
@property(nonatomic,strong)NSArray  *threeArr;
@property (nonatomic,weak)WYCbankPickerView  *bankPickerView;
@property (nonatomic,strong) NSMutableArray *resultArray;
@property (nonatomic, strong) UIToolbar *toolBar;
@property(nonatomic,strong)WYCBankModel *bankModel;
@property(nonatomic,strong)WYCDayPickerView *DayPickerView;
@property(nonatomic,strong)UIButton * check;
@property(nonatomic,strong) UIButton * loginButton1;

@property(nonatomic,strong)UIButton * borrow;

@property(nonatomic,strong)UITextField  *cardnumber;

@property(nonatomic,strong)UITextField  *cvn2;
@property(nonatomic,strong)UITextField  *amount;

@property(nonatomic,strong)UITextField  *name;

@property(nonatomic,strong)UITextField  *phone;

@end

@implementation WQCAddViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"bnakid%@",_bankidStr);
    self.navigationController.navigationBarHidden =NO;
    self.resultArray = [[NSMutableArray alloc] init];

    self.view.backgroundColor = WYCGlobalBg;
    [self setupNav];
    [self loadPickBank];
    _oneArr = @[@"信用卡号",@"发卡银行",@"有效日期",@"SVN2"];
    _twoArr = @[@"总额度",@"账单日",@"还款日"];
    _threeArr = @[@"持卡人姓名",@"预留手机号"];
    
    
    self.editTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH) style:UITableViewStyleGrouped];
    self.editTableView.dataSource = self;
    self.editTableView.delegate = self;
    self.editTableView.sectionFooterHeight = 10;
    self.editTableView.sectionHeaderHeight = 10;
    [self.view addSubview:self.editTableView];
    
}
-(void)loadAddBank
{
    
    if (_cardnumber.text.length == 0) {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"信用卡号不能为空"];

        return;
    }
    else if (_bankidStr.length == 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"发卡银行不能为空"];

        return;
    }
    else if (bankname.titleLabel.text.length == 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"有效日期不能为空"];

        return;
    }
    else if (_cvn2.text.length == 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"cvn2不能为空"];
        return;
    }
    else if (_amount.text.length==0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"总额度不能为空"];

        return;
    }
    else if (self.check.titleLabel.text.length == 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"账单日不能为空"];
        return;
    }
    else if (self.borrow.titleLabel.text.length == 0)
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"还款日不能为空"];
        return;
    }
    else if (_phone.text.length == 0)
        
    {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"预留手机号不能为空"];
        return;
    }
    else{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];

    NSLog(@"增加%@%@%@",_cardnumber.text,self.bankidStr,bankname.titleLabel.text);
    NSDictionary * jsonStr = @{@"cardNumber":_cardnumber.text,@"bankId":self.bankidStr,@"validity":bankname.titleLabel.text,@"cVN2":_cvn2.text,@"creditLine":_amount.text,@"mobile":_phone.text,@"billDate":self.check.titleLabel.text,@"dueDate":self.borrow.titleLabel.text};
    NSLog(@"用户添加%@",jsonStr);

    NSError *error;
    
    NSData * data = [NSJSONSerialization dataWithJSONObject:jsonStr options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSString *pas = [RSA encryptString:jsonString publicKey:RSA_P_KEY];
    
    params[@"request"] = pas;
    [HttpTool POST:addabank params:params success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"返回%@",responseObject);

        if ([[responseObject objectForKey:@"code"] intValue] == 0) {
            [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"增加信用卡成功"];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else{
            
            [SVProgressHUD showImage:[UIImage imageNamed:@""] status:msgStr];
        }
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:Failed];
    }];
    }
}
-(void)loadEditBank
{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    NSDictionary * jsonStr = @{@"cardId":_cardidStr,@"cardNumber":_cardnumber.text,@"bankId":self.bankidStr,@"validity":bankname.titleLabel.text,@"cVN2":_cvn2.text,@"creditLine":_amount.text,@"mobile":_phone.text,@"billDate":self.check.titleLabel.text,@"dueDate":self.borrow.titleLabel.text};
    NSLog(@"用户添加%@",jsonStr);
    
    NSError *error;
    
    NSData * data = [NSJSONSerialization dataWithJSONObject:jsonStr options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSString *pas = [RSA encryptString:jsonString publicKey:RSA_P_KEY];
    
    params[@"request"] = pas;
    [HttpTool POST:editCreditCard params:params success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"返回%@",responseObject);
        
        if ([[responseObject objectForKey:@"code"] intValue] == 0) {
            [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"绑定成功"];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else{
            
            [SVProgressHUD showImage:[UIImage imageNamed:@""] status:msgStr];
        }
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:Failed];
    }];
}
- (void)setupNav {
    if ([self.myFlag  isEqualToString:@"777"])
    {
        self.navigationItem.title = @"智能信用卡管家";
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTitle:@"保存" target:self action:@selector(saveButtonClick)];

    }
    else
    {
        self.navigationItem.title = @"添加信用卡";
    }
    [self.navigationController.navigationBar setBarTintColor:wycMain];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];


}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
//保存
-(void)saveButtonClick
{
    if ([self.myFlag  isEqualToString:@"777"])
    {
        [self loadEditBank];
    }
    else
    {
        [self loadAddBank];
    }
}
#pragma mark - TableView DataSource Method

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section  == 0) {
        return _oneArr.count;
    }
    else if (section ==1)
    {
        return _twoArr.count;
    }
    else if(section == 2)
    {
        return _threeArr.count;
        
    }
    else
        return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * strID = @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:strID];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 0) {
        cell.textLabel.text =[_oneArr objectAtIndex:indexPath.row];
        if (indexPath.row == 0) {
            _cardnumber = [[UITextField alloc]init];
            _cardnumber.frame = CGRectMake(120, 10, ScreenWidth-150, 30);
            _cardnumber.placeholder = @"请输入银行卡号";
            _cardnumber.font = [UIFont systemFontOfSize:14];
            _cardnumber.text = self.cardNumberStr;
            [cell.contentView addSubview:_cardnumber];
            
        }
        else if (indexPath.row ==1)
        {
            _loginButton1 = [MyUIClass makeUIButtonWithFrame:CGRectMake(120, 10,ScreenWidth-100, 30) andType:UIButtonTypeRoundedRect andTitle:@"请选择银行" andImageName:@"" andTarget:self andSelector:@selector(pressPickbank) andEvent:UIControlEventTouchUpInside andState:UIControlStateNormal];
            _loginButton1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

            _loginButton1.titleLabel.font = [UIFont systemFontOfSize:14];
            [_loginButton1 setTitle:_nameStr forState:UIControlStateNormal];
            [_loginButton1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [cell.contentView addSubview:_loginButton1];

            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
            
        }
        else if (indexPath.row == 2)
        {
           bankname = [MyUIClass makeUIButtonWithFrame:CGRectMake(120, 10, ScreenWidth-100, 30) andType:UIButtonTypeCustom andTitle:@"请选择有效期" andImageName:@"" andTarget:self andSelector:@selector(bottonClick) andEvent:UIControlEventTouchUpInside andState:UIControlStateNormal];
            [bankname setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            bankname.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            bankname.titleLabel.font = [UIFont systemFontOfSize:14];

            [bankname setTitle:self.validityStr forState:UIControlStateNormal];
            [cell.contentView addSubview:bankname];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
            
        }
        if (indexPath.row == 3) {
            _cvn2 = [[UITextField alloc]init];
            _cvn2.frame = CGRectMake(120, 10, 250, 30);
            _cvn2.placeholder = @"请输入卡后面三位数";
            _cvn2.font = [UIFont systemFontOfSize:14];
            _cvn2.text =self.cvn2str;
            [cell.contentView addSubview:_cvn2];
            
        }
    }
    else if (indexPath.section == 1)
    {
        cell.textLabel.text =[_twoArr objectAtIndex:indexPath.row];
        if (indexPath.row == 0) {
            _amount = [[UITextField alloc]init];
            _amount.frame = CGRectMake(120, 10, 250, 30);
            _amount.placeholder = @"请输入总额度";
            _amount.textAlignment =NSTextAlignmentLeft;
            _amount.font = [UIFont systemFontOfSize:14];
            _amount.text = self.amontStr;
            [cell.contentView addSubview:_amount];
        }
        
        else if (indexPath.row == 1)
        {
          UIButton *  bankname = [MyUIClass makeUIButtonWithFrame:CGRectMake(120, 10, ScreenWidth-100, 30) andType:UIButtonTypeCustom andTitle:@"请选择账单日" andImageName:@"" andTarget:self andSelector:@selector(chekClick) andEvent:UIControlEventTouchUpInside andState:UIControlStateNormal];
            [bankname setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            bankname.titleLabel.font = [UIFont systemFontOfSize:14];
            bankname.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            [bankname setTitle:_billDay forState:UIControlStateNormal];
            [cell.contentView addSubview:bankname];
            self.check = bankname;

            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
            
        }
        else if (indexPath.row == 2)
        {
            UIButton  *bankname = [MyUIClass makeUIButtonWithFrame:CGRectMake(120, 10, ScreenWidth-100, 30) andType:UIButtonTypeCustom andTitle:@"请选择还款日" andImageName:@"" andTarget:self andSelector:@selector(pressborrbank) andEvent:UIControlEventTouchUpInside andState:UIControlStateNormal];
            bankname.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            [bankname setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            self.borrow = bankname;
            [bankname setTitle:self.dueDateStr forState:UIControlStateNormal];
            [cell.contentView addSubview:bankname];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
            
        }
    }
    else if (indexPath.section == 2)
    {
        cell.textLabel.text =[_threeArr objectAtIndex:indexPath.row];
        if (indexPath.row == 0) {
            _name= [[UITextField alloc]init];
            _name.frame = CGRectMake(120, 10, 250, 30);
            _name.placeholder = @"请输入姓名";
            _name.text = [WYCAccountTool unarchiveuserName];
            _name.font = [UIFont systemFontOfSize:14];
            _name.enabled =NO;
            [cell.contentView addSubview:_name];
        }
        if (indexPath.row == 1) {
              _phone = [[UITextField alloc]init];
            _phone.frame = CGRectMake(120, 10, 250, 30);
            _phone.placeholder = @"请输入预留手机号";
            _phone.text = self.mobileStr;
            _phone.font = [UIFont systemFontOfSize:14];
            [cell.contentView addSubview:_phone];
        }
    }
    else
    {
        
        if ([self.myFlag  isEqualToString:@"777"])
        {
            cell.textLabel.text = @"删除卡片";

        }
        else
        {
            cell.textLabel.text = @"提交";

        }

        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.textColor = wycMain;
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section ==3) {
      //删除卡片
        if ([self.myFlag  isEqualToString:@"777"])
        {
            [self deleteBank];

        }
        else
        {
            [self loadAddBank];
        }
    }
}
-(void)deleteBank
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
  
    params[@"cardId"] = self.cardidStr;
    [HttpTool POST:CreditCardDelete params:params success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"删除信用卡%@",responseObject);
        
        if ([[responseObject objectForKey:@"code"] intValue] == 0) {
            [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"删除信用卡成功"];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else{
            
            [SVProgressHUD showImage:[UIImage imageNamed:@""] status:msgStr];
        }
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:Failed];
    }];

}
//选择银行
-(void)pressPickbank
{
    [self.cardnumber resignFirstResponder];
    [self.bankPickerView removeFromSuperview];
    WYCbankPickerView *bankView = [[WYCbankPickerView alloc]initWithSourceData:self.resultArray confirmBlock:^(WYCBankModel *bankModel) {
        _bankModel = bankModel;
        [_loginButton1 setTitle:bankModel.bankName forState:UIControlStateNormal];
        self.bankidStr = bankModel.bankId;
        [self pickerViewhide:YES];
        
    } cancelBlock:^(WYCBankModel *bankModel) {
        [_loginButton1 setTitle:bankModel.bankName forState:UIControlStateNormal];
        [self pickerViewhide:YES];

        
    }];
    bankView.frame = CGRectMake(0, ScreenHeight-200, ScreenWidth, 200);
    self.bankPickerView = bankView;
    [self.view addSubview:self.bankPickerView];
    [self pickerViewhide:NO];
}
- (void)pickerViewhide:(BOOL)hide {
    
    if (hide) {
        
        [UIView animateWithDuration:1 animations:^{
            
            
            self.bankPickerView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, 280);
        }];
    }else {
        
        [UIView animateWithDuration:1 animations:^{
            
            self.bankPickerView.frame = CGRectMake(0, ScreenHeight - 200, ScreenWidth, 200);
        }];
    }
    
}
-(void)loadPickBank
{
    
    [HttpTool POST:banklist params:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",responseObject);
        if ([[responseObject objectForKey:@"code"] intValue] == 0) {
            NSArray * resultArray = responseObject[@"result"];
            for (NSDictionary * dict in resultArray) {
                WYCBankModel * model = [WYCBankModel mj_objectWithKeyValues:dict];
                [self.resultArray addObject:model];
                self.bankModel = _bankModel;
                
            }
        }
        [self.bankPickerView refreshWithSourceData:self.resultArray];
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
   
}
-(void)pressborrbank
{
    [self.DayPickerView removeFromSuperview];
    [self setDayPickerView:nil];
    
    
    
    
    NSMutableArray *checkArray = [NSMutableArray new];
    for (int i = 0; i < 31; i ++) {
        [checkArray addObject:[NSString stringWithFormat:@"%d",i+1]];
    }
        self.DayPickerView = [[WYCDayPickerView alloc]initWithSourceData:checkArray confirmBlock:^(NSString *dayStr) {
            [self.borrow setTitle:[NSString stringWithFormat:@"%@",dayStr] forState:UIControlStateNormal];
            [self.view endEditing:YES];
            
            [self hideView];
            
        } cancelBlock:^(NSString *dayStr) {
            [self.view endEditing:YES];
            [self hideView];
        }];
        
        
        self.DayPickerView.frame  = CGRectMake(0, ScreenHeight - 300, ScreenWidth, 300);
        [self.view addSubview:self.DayPickerView];
    
}
//有效期
- (void)bottonClick {
    
    __weak __typeof(self) weakself = self;
    pickerView =[[PickerDateViewController alloc]init];
    [self.view addSubview:pickerView.view];
    pickerView.selectedBlock = ^(NSString * selectedDate){
        
        NSString *yearStr = [selectedDate stringByReplacingOccurrencesOfString:@"年" withString:@"-"];
        NSString *titleStr = [yearStr stringByReplacingOccurrencesOfString:@"月" withString:@""];
        
        [weakself buttonTitle:titleStr];
    };
    
}
- (void)chekClick{
    
    [self.DayPickerView removeFromSuperview];
    [self setDayPickerView:nil];
    
    NSMutableArray *checkArray = [NSMutableArray new];
    for (int i = 0; i < 31; i ++) {
        [checkArray addObject:[NSString stringWithFormat:@"%d",i+1]];
    }
    __weak __typeof(self) weakSelf = self;
        self.DayPickerView = [[WYCDayPickerView alloc]initWithSourceData:checkArray confirmBlock:^(NSString *dayStr) {
            [weakSelf.check setTitle:[NSString stringWithFormat:@"%@",dayStr] forState:UIControlStateNormal];
            [weakSelf.view endEditing:YES];
            
            [weakSelf hideView];
            
        } cancelBlock:^(NSString *dayStr) {
            [weakSelf.view endEditing:YES];
            [weakSelf hideView];
        }];
        
        
        self.DayPickerView.frame  = CGRectMake(0, ScreenHeight - 300, ScreenWidth, 300);
        [self.view addSubview:self.DayPickerView];
   
}

- (NSString *)buttonTitle:(NSString *)title{
    [bankname setTitle:title forState:UIControlStateNormal];
    
    
    return title;
}
- (void)hideView{
    
    [self.DayPickerView setHidden:YES];
    
    
}

@end
